<template>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="周边">
        </el-tab-pane>
        <el-tab-pane label="装备">
        </el-tab-pane>
    </el-tabs>
    <div class="common-layout">
        <el-container>
            <el-aside width="200px">
                <el-row style="width: 100%;">
                    <el-input v-model="styleZzxcsm" placeholder="添加分类" @keyup.enter="addCategory(activeName)" />
                </el-row>
                <el-table :data="tableData" style="width: 100%; height:488px">
                    <el-table-column prop="style" label="分类名称">
                        <template #default="scope">
                            <el-button @click="getGoods(scope.row.id)" style="width: 80px;">{{ scope.row.style
                            }}</el-button>
                            <el-button type="primary" @click="showAddDialog(scope.row)" :icon="PlusOutlined"
                                style="width: 30px;" />
                            <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢"
                                :icon="InfoFilled" icon-color="#626AEF" title="你确定要删除这条数据吗?"
                                @onConfirm="deleteCategory(scope.row)" @confirm="deleteCategory(scope.row)">
                                <template #reference>
                                    <el-button type="danger" style="width: 30px;" :icon="DeleteOutlined"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </el-aside>
            <el-main>
                <!-- 商品列表 -->
                <el-table :data="goodsTableData" style="width: 100%; height:500px">
                    <el-table-column prop="title" label="商品名称" />
                    <el-table-column prop="price" label="商品价格" />
                    <el-table-column label="商品图片">
                        <template #default="scope">
                            <img :src="scope.row.imgurl[0]" style="width: 50px; height: 50px;" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="上架状态">
                        <template #default="scope">
                            <el-switch v-model="scope.row.status" @change="changeState(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="180">
                        <template #default="scope">
                            <el-button type="primary" :icon="EditOutlined" @click="editGoods(scope.row)"></el-button>
                            <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢"
                                :icon="InfoFilled" icon-color="#626AEF" title="你确定要删除这条数据吗?"
                                @onConfirm="deleteGoods(scope.row)" @confirm="deleteGoods(scope.row)">
                                <template #reference>
                                    <el-button type="danger" :icon="DeleteOutlined"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-pagination style="margin-top: 20px;" v-model:currentPage="currentPage" v-model:pageSize="pageSize"
                    :page-sizes="[2, 5, 7, 10]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                <!-- 商品列表 -->
            </el-main>
        </el-container>
    </div>
    <!-- 添加商品 -->
    <el-dialog v-model="addDialogFormVisible" :title="addForm.dialogTitle">
        <el-form :model="addForm" :rules="addRules" ref="addRuleFormRef">
            <!-- <el-form :model="addForm" :rules="rules" ref="ruleFormRef"> -->
            <el-form-item label="商品名称" :label-width="formLabelWidth" prop="title">
                <el-input v-model="addForm.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                <el-input v-model="addForm.price" autocomplete="off" type="number" />
            </el-form-item>
            <el-form-item label="商品图片" :label-width="formLabelWidth" prop="imgurl">
                <el-upload action="http://localhost:9999/zzxcsm/upload" :on-preview="handlePreview" :on-remove="handleRemove"
                :file-list="fileList" list-type="picture-card" class="upload-demo" :headers="uploadHeaders"
                :on-success="onSuccess">
                <el-button type="primary">上传商品详情图片</el-button>
                <template #tip>
                    <div class="el-upload_tip">
                        图片要求：jpg/png文件格式，500kb以内。
                    </div>
                </template>
            </el-upload>
            </el-form-item>
            <el-form-item label="上架状态" :label-width="formLabelWidth" prop="status">
                <el-radio-group v-model="addForm.status">
                    <el-radio label="上架" :value="1"></el-radio>
                    <el-radio label="下架" :value="0"></el-radio>
                </el-radio-group>
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="addSubmitForm(addRuleFormRef)">提交</el-button>
                <el-button @click="addResetForm(addRuleFormRef)">
                    重置
                </el-button>
            </span>
        </template>
    </el-dialog>
      <!-- 编辑商品对话框 -->
      <el-dialog v-model="editDialogFormVisible" title="编辑用户" :before-close="handleBeforeClose">
        <el-form :model="editForm" :rules="editRules" ref="editRuleFormRef">
            <el-form-item label="商品名称" :label-width="formLabelWidth" prop="title">
                <el-input v-model="editForm.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                <el-input v-model="editForm.price" autocomplete="off" type="number"/>
            </el-form-item>
            <el-form-item label="商品图片" :label-width="formLabelWidth" prop="imgurl">
                <el-upload action="http://localhost:9999/zzxcsm/upload" :on-preview="editHandlePreview" :on-remove="editHandleRemove"
                :file-list="editFileList" list-type="picture-card" class="upload-demo" :headers="editUploadHeaders"
                :on-success="editOnSuccess">
                <el-button type="primary">上传商品详情图片</el-button>
                <template #tip>
                    <div class="el-upload_tip">
                        图片要求：jpg/png文件格式，500kb以内。
                    </div>
                </template>
            </el-upload>
            </el-form-item>
            <el-form-item label="上架状态" :label-width="formLabelWidth" prop="status">
                <el-radio-group v-model="editForm.status">
                    <el-radio label="上架" :value="true"></el-radio>
                    <el-radio label="下架" :value="false"></el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="editSubmitForm(editRuleFormRef)">提交</el-button>
                <el-button @click="editResetForm(editRuleFormRef)">
                    重置
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { InfoFilled } from '@element-plus/icons-vue'
import axios from '../../axios.js';
import { ref, onBeforeMount, watchEffect, reactive } from 'vue'
import { ElMessage } from 'element-plus';
import { get } from 'lodash';
/* 获取根据category获取商品分类数据 */
const activeName = ref(0)
const tableData = ref([]);
let netData = ref([])
const getCategory = async () => {
    const type = activeName.value == 0 ? 2 : 3
    const { data: res } = await axios.get(`/category/list/${type}`)
    console.log(res);
    tableData.value = [];
    res.data.forEach(ele => {
        tableData.value.push({
            id: ele.idZzxcsm,
            style: ele.styleZzxcsm
        });
    })
    netData.value = tableData.value
}
getCategory()
/* 添加分类 */
const styleZzxcsm = ref('')
const addCategory = async (type) => {
    if (styleZzxcsm.value != "") {
        const { data: res } = await axios.post(`/category`, {
            styleZzxcsm: styleZzxcsm.value,
            typeZzxcsm: type == 0 ? 2 : 3
        })
        console.log(res);
        if (res.code == 1) {
            ElMessage.success("添加分类成功");
            getCategory()
        }
        else ElMessage.error("添加分类失败")
    } else {
        ElMessage.error("请输入分类名称")
    }
}
/* 删除分类 */
const deleteCategory = async (row) => {
    console.log(row);
    const { data: res } = await axios.delete(`/category/${row.id}`)
    if (res.code == 1) {
        ElMessage.success("成功删除分类");
        getCategory()
    } else {
        ElMessage.error(res.msg);
    }
}
/* 删除商品 */
const deleteGoods = async (row) => {
    console.log(row);
    const { data: res } = await axios.delete(`/goods/${row.id}`)
    if (res.code == 1) {
        ElMessage.success("成功删除商品");
        getCategory()
    } else {
        ElMessage.error(res.msg);
    }
}
/* 根据category_id 获取商品列表 */
/* 分页 */
const nowCategory = ref('')
const total = ref(1)
const currentPage = ref(1)
const pageSize = ref(3)
const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    pageSize.value = val
    // getCategory()
    getGoods(nowCategory.value)
}
const handleCurrentChange = (val) => { console.log(`current page:${val}`); currentPage.value = val; getGoods(nowCategory.value) }
const goodsTableData = ref([]);
let goodsNetData = ref([])
const getGoods = async (category_id) => {
    nowCategory.value = category_id
    const { data: res } = await axios.get(`/goods/page/${category_id}`, {
        params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value
        }
    })
    console.log(res);
    goodsTableData.value = [];
    res.data.records.forEach(ele => {
        goodsTableData.value.push({
            id: ele.idZzxcsm,
            category: ele.categoryZzxcsm,
            title: ele.titleZzxcsm,
            price: ele.priceZzxcsm,
            imgurl: ele.imgurlZzxcsm.split(","),
            status: ele.statusZzxcsm == 1 ? true : false
        });
    })
    total.value = res.data.total
    goodsNetData.value = goodsTableData.value
}
getCategory()
/* 切换商品状态 */
const changeState = async (goods) => {
    console.log(goods);
    var s = goods.status === true ? 1 : 0
    const { data: res } = await axios.put(`goods/${goods.id}/status/${s}`)
}
/* 新建商品 */
const formLabelWidth = '140px';
const addDialogFormVisible = ref(false)
const addForm = reactive({
    dialogTitle:'',
    title: '',
    categoryId:'',
    price: '',
    imgurl: [],
    status: ''
})
const showAddDialog = (val)=>{
    addDialogFormVisible.value = true
    console.log(val);
    addForm.dialogTitle = `向 ${val.style} 中添加商品`
    addForm.categoryId = val.id
    console.log(addForm);
}
// 表单验证
const addRuleFormRef = ref(null)
const addRules = reactive({
    title: [{
        required: true, message: '请输入商品名称', trigger: 'blur'
    }],
    price: [{
        required: true, message: '请输入商品单价', trigger: 'blur'
    },{
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback(); // 校验通过
        } else {
          callback(new Error('价格必须大于0')); // 校验不通过
        }
      }, trigger: 'blur'
    }],
    imgurl: [{
        required: true, message: '请为商品选择至少一张图片', trigger: 'blur'
    }],
    status: [{
        required: true, message: '请决定商品是否立即上架', trigger: 'blur'
    }],
})
// 提交表单
const addSubmitForm = async (formEL) => {
    console.log(addForm);
    if (!formEL) return
    const f =  addRuleFormRef.value.validate((valid) => {return valid})
    console.log(f);

    const { data: res } = await axios.post('/goods', {
        categoryIdZzxcsm:addForm.categoryId,
        titleZzxcsm:addForm.title,
        priceZzxcsm:addForm.price,
        imgurlZzxcsm:addForm.imgurl.join(","),
        statusZzxcsm:addForm.status === "上架"?1:0
    })
    console.log(res);
    if (res.code === 1) {
        getGoods(addForm.categoryId)
        addDialogFormVisible.value = false
        ElMessage.success("新建成功！")
    } else {
        ElMessage.error(res.msg)
    }

}
// 清空表单
const addResetForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields()
}
/* 商品图片 */
const dialogImageUrl = ref('')
const dialogImageAlt = ref('')
const fileList = ref([
])
// 删除图片
const handleRemove = (uploadFile, uploadFiles) => {
  exForm.ex_detail = exForm.ex_detail.filter(item => item != uploadFile.response.data)
}
const handlePreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true
  dialogImageAlt.value = file.name
}
// 上传图片
const uploadHeaders = {
    Authorization: window.localStorage.getItem('token')
}
const onSuccess = (val) => {
  addForm.imgurl.push(val.data)
  console.log("文件列表");
  console.log(fileList);
}
/* 编辑图片 */
const editDialogImageUrl = ref('')
const editDialogImageAlt = ref('')
const editFileList = ref([
])
// 删除图片
const editHandleRemove = (uploadFile, uploadFiles) => {
    editForm.urlimg = editForm.imgurl.filter(item => item != uploadFile.response.data)
}
const editHandlePreview = (file) => {
    editDialogImageUrl.value = file.url
    editDialogFormVisible.value = true
    editDialogImageAlt.value = file.name
}
// 上传图片
const editUploadHeaders = {
    Authorization: window.localStorage.getItem('token')
}
const editOnSuccess = (val) => {
  editForm.imgurl.push(val.data)
}
const handleBeforeClose= ()=>{
    editDialogFormVisible.value = false
    editFileList.value = []
}
/* 编辑对话框 */
const editDialogFormVisible = ref(false)
const editForm = reactive({
    title: '',
    categoryId:'',
    price: '',
    imgurl: [],
    status: ''
})
const editGoods = (goods) => {
    console.log(goods);
    editDialogFormVisible.value = true;
    editForm.title = goods.title
    editForm.price = goods.price
    editForm.imgurl = goods.imgurl
    editForm.status = goods.status
    goods.imgurl.forEach(ele => {
        editFileList.value.push({name:ele.split(".")[-1],url:ele})
    });
    console.log(editForm);
}
// 表单验证
const editRuleFormRef = ref(null)
const editRules = reactive({
    title: [{
        required: true, message: '请输入商品名称', trigger: 'blur'
    }],
    price: [{
        required: true, message: '请输入商品单价', trigger: 'blur'
    },{
      validator: (rule, value, callback) => {
        if (value > 0) {
          callback(); // 校验通过
        } else {
          callback(new Error('价格必须大于0')); // 校验不通过
        }
      }, trigger: 'blur'
    }],
    imgurl: [{
        required: true, message: '请为商品选择至少一张图片', trigger: 'blur'
    }],
    status: [{
        required: true, message: '请决定商品是否立即上架', trigger: 'blur'
    }],
})
// 提交表单
const editSubmitForm = async (formEL) => {
    if (!formEL) return
    editForm.categoryId = nowCategory.value
    console.log(editForm);
    const { data: res } = await axios.put('/goods', {
        categoryIdZzxcsm:editForm.categoryId,
        titleZzxcsm:editForm.title,
        priceZzxcsm:editForm.price,
        imgurlZzxcsm:editForm.imgurl.join(","),
        statusZzxcsm:editForm.status === "上架"?1:0
    })
    console.log(res);
    if (res.code === 1) {
        getGoods(editForm.categoryId)
        editDialogFormVisible.value = false
        editFileList.value = []
        ElMessage.success("修改成功！")
    } else {
        editFileList.value = []
        ElMessage.error(res.msg)
    }

}
// 清空表单
const editResetForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields()
}

/* 切换tab时的事件 */
const handleClick = (tab, event) => {
    activeName.value = tab.index
    goodsNetData.value.length = 0
    getCategory()
}
</script>

<style scoped></style>
